package com.aaa.util;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class IDCard {
    private static final String FIELD_SECRET_ID = "AKIDsZ0A3f04sPfeNp0uYw2rPggPr3ycz6wV";//填写secretId
    private static final String FIELD_SECRET_KEY = "KNAgurZ0ymLfkZ9UZPyIL7crpWw60d06";//填写secretKey
    private static final String FIELD_TENCENT_CLOUD_API = "ocr.tencentcloudapi.com";//接口请求域名： ocr.tencentcloudapi.com
    private static final String FIELD_REGION = "ap-guangzhou";//地域


    /**
     * 获取OcrClient.
     * @return ocrClient
     */
    private static OcrClient getOcrClient(){
        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        Credential cred = new Credential(FIELD_SECRET_ID, FIELD_SECRET_KEY);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        // 指定接入地域域名(默认就近接入
        httpProfile.setEndpoint(FIELD_TENCENT_CLOUD_API);
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        // 自3.1.80版本开始，SDK 支持打印日志。
        clientProfile.setHttpProfile(httpProfile);
        /**
         * 获取OcrClient对象
         * cred : 认证对象 根据secretId 与 secretKey 获取
         * FIELD_REGION : 地域参数，建议您阅读文档了解地域以及计费情况
         * clientProfile : client选项
         */
        OcrClient ocrClient = new OcrClient(cred, FIELD_REGION, clientProfile);
        return ocrClient;
    }
    /**
     * 身份证识别.
     * @param imageStr
     * @return
     */
    private static String getIdcardOcr(String imageStr) {
        //获取OcrClient.
        OcrClient ocrClient = getOcrClient();
        try {
            IDCardOCRRequest req = new IDCardOCRRequest();
            //写入Base64格式图片
            req.setImageBase64(imageStr);
            //解析和返回结果
            IDCardOCRResponse resp = ocrClient.IDCardOCR(req);
            return IDCardOCRResponse.toJsonString(resp);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 根据byte字节转换为Base64图片
     * @param in MultipartFile的输入流
     * @return
     */
    public static String getBase64FromInputStream(InputStream in) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            //输出：将输入流读取的东西写到另一个文件
            ByteArrayOutputStream swapStream  = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc=in.read(buff, 0, 100)) > 0){
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String s = new String(Base64.encodeBase64(data));
        return getIdcardOcr(s);
    }
    /**
     * 网络图片转Base64
     * @param remark  地址路径
     * @return
     */
    public static String encodeImageToBase64ToIDCard(String remark) {
        ByteArrayOutputStream outputStream = null;

        try {
            URL url = new URL(remark);
            BufferedImage bufferedImage = ImageIO.read(url);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String s= encoder.encode(outputStream.toByteArray());
        return getIdcardOcr(s);
    }
}
